﻿using LY.Entity;
using LY.Entity.Entities;
using LY.Entity.Jsons;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Interface;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QJ.CMS.Filters;
using System.IO;
using System.Drawing;


namespace QJ.CMS.Controllers
{
    public class ProjectController : Controller
    {
        //项目
        // GET: /Project/
        private IProjectItemService _proItem;
        private IProjectService _pro;
        private IMemberService _mem;
        private IBankCardService _bank;
        private IBankInfoService _bankInfo;
        public ProjectController(IProjectItemService proItem, IProjectService pro, IMemberService mem, IBankCardService bank, IBankInfoService bankInfo)
        {
            _proItem = proItem;
            _pro = pro;
            _mem = mem;
            _bank = bank;
            _bankInfo = bankInfo;
        }

        //发起项目
        public ActionResult Index()
        {
            return View();
        }

        #region 项目
        //发起项目界面
        [MyAuthorization]
        public ActionResult AddProject(int id = 0)
        {
            R_Project pro = null;
            var member = (U_Member)Session["CurrentUser"];
            bool trueORfalse = true;
            if (id > 0)
            {
                trueORfalse = _pro.IsProjectOwnedUser(id, member.ID);
                //根据项目ID查询会员ID 及项目状态
                R_Project project = _pro.GetProject(id);
                //判断当前项目的状态：如果是已审核：不能修改
                if (trueORfalse == true && (project.ProjectStatus == 0 || project.ProjectStatus == 3))
                {
                    //编辑
                    pro = _pro.GetProject(id);
                }
                else
                {
                    return RedirectToAction("Error", "Default");
                }
            }
            else
            {
                pro = new R_Project();
                pro.MemberId = member.ID;
                //这里开始给众筹项目命名

            }
            return View(pro);
        }

        //添加项目
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult SaveProject(R_Project pro, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                int projectid = 0;
                pro.AddTime = DateTime.Now;
                // pro.ProjectStatus = (int)LY.Common.Enum.ProjectStatus.已保存;
                pro.AuditStatus = (int)LY.Common.Enum.ProjectStatus.已保存;
                pro.ProjectThumImage1_small = pro.ProjectThumImage1.Replace(".", "_small.");

                int ret = _pro.SaveProject(pro);
                //判断
                if (pro.Id != 0)
                {
                    projectid = pro.Id;
                }
                else
                {
                    projectid = ret;
                }

                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                    rMsg.Data = Url.Action("AddProjectItem", "Project", new { proid = projectid });
                 
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //修改项目的状态
        [HttpPost]
        public JsonResult UpdateProjectStatus(FormCollection formCollection, U_BankCard bankCard)
        {
            var rMsg = new JsonSMsg();
            try
            {
                //U_BankInfo bankInfo = _bankInfo.GetBankInfo(bankCard.CardName);
                // bankCard.BankName = bankInfo.BankName;
                bankCard.AddTime = DateTime.Now;
                long ret2 = _bank.BindCard(bankCard);

                string action = formCollection["btnSave"];
                if (action == "提交")
                {
                    var projectid = Convert.ToInt32(formCollection["ProjectId"]);
                    R_Project pro = _pro.GetProject(projectid);
                    //  pro.ProjectStatus = (int)LY.Common.Enum.ProjectStatus.审核中;
                    pro.AuditStatus = (int)LY.Common.Enum.ProjectStatus.初选;
                    int ret = _pro.SaveProject(pro);
                    if (ret > 0 && ret2 > 0)
                    {
                        rMsg.Status = 1;
                        rMsg.Message = "项目提交成功！";
                        rMsg.Data = "/Project/Submit";
                    }
                    else
                    {
                        rMsg.Status = -1;
                        rMsg.Message = "意外错误，请稍后重试！";
                    }
                }
                else
                {
                    if (ret2 > 0)
                    {
                        rMsg.Status = 1;
                        rMsg.Message = "项目保存成功！";
                        rMsg.Data = Url.Action("MyProject", "UserProject");
                    }
                    else
                    {
                        rMsg.Status = -1;
                        rMsg.Message = "意外错误，请稍后重试！";
                    }

                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }


        #endregion

        #region 回报
        //回报界面
        [ValidateInput(false)]
        [MyAuthorization]
        public ActionResult AddProjectItem(int? id, int proid = 0)
        {
            var projectItem = new R_ProjectItem
                {
                    ProjectId = proid
                };
            ViewBag.sign = 2;
            var member = (U_Member)Session["CurrentUser"];

            if (!_pro.IsProjectOwnedUser(Convert.ToInt32(projectItem.ProjectId), member.ID))
            {
                return RedirectToAction("Error", "Default", new { msg = "非法操作！" });
            }

            if (id > 0)
            {
                ViewBag.sign = 1;
                projectItem = _proItem.GetProjectItem(id);
            }
            return View(projectItem);
        }

        //新增或编辑回报
        [HttpPost]
        public JsonResult ProjectItemSave(R_ProjectItem pro, FormCollection collection)
        {
            var rMsg = new JsonSMsg();
            try
            {
                if (pro.Limits == null)
                {
                    pro.Limits = 0;
                }

                if (pro.Freight == null)
                {
                    pro.Freight = 0;
                }

                int ret = _pro.SaveProjectItem(pro);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    Session["sign"] = 1;
                    rMsg.Data = Url.Action("AddProjectItem", "Project", new { proid = pro.ProjectId });
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //删除回报设置
        [HttpPost]
        public JsonResult DeleteProjectItem(int id)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                }

                int ret = _proItem.deleteProjectItem(id);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {

                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //获取回报列表
        [HttpPost]
        public ActionResult ProjectItem(ProjectItemSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];

            PagedList<R_ProjectItem> rList = _proItem.GetProjectItem(search.ProjectId, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<R_ProjectItem>(rList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        #endregion

        #region 项目确认信息
        [ValidateInput(false)]
        [MyAuthorization]
        public ActionResult ConfirmProject(int proid)
        {
            U_Member member = Session["CurrentUser"] as U_Member;
            U_BankCard BankCard = _bank.GetCardByProId(proid);
            ViewBag.bankcard = BankCard;
            ViewBag.Proid = proid;
            ViewBag.memberId = member.ID;


            if (!_pro.IsProjectOwnedUser(proid, member.ID))
            {
                return RedirectToAction("Error", "Default", new { msg = "非法操作！" });
            }

            return View();
        }
        //获取会员绑定的银行卡
        [HttpPost]
        public ActionResult BindBankcard(int id)
        {
            List<U_BankCard> bankCards = _bank.GetbankcardList(id);
            return Json(bankCards);
        }


        #endregion

        //提交
        public ActionResult Submit()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Cainixihuang(int isRefresh = 0)
        {
            var rMsg = new JsonSMsg();

            if (isRefresh != 0)
            {
                rMsg.Data = _pro.CainiXihuang();
                Session["cnxh"] = rMsg.Data;
            }
            else
            {
                rMsg.Data = Session["cnxh"] as List<R_Project_EX> ?? _pro.CainiXihuang();
            }
            return Json(rMsg);
        }

        #region 项目答疑/提问

        //我的问题列表
        [HttpPost]
        public ActionResult MyQuestionList(string pid)
        {
            U_Member u = Session["CurrentUser"] as U_Member;
            if (u != null)
            {
                return Json(_pro.GetMyQuestionList(u.ID.ToString(), pid));
            }
            else
            {
                return Json("Undefined");
            }
        }

        //公开问题列表
        [HttpPost]
        public ActionResult QuestionList(string pid)
        {
            return Json(_pro.GetQuestionList(pid));
        }

        //提交问题
        [HttpPost]
        public ActionResult SubmitQuestion(R_projectQuestion question)
        {
            JsonSMsg msg = new JsonSMsg();

            question.CreateTime = DateTime.Now;
            question.MemberId = (Session["CurrentUser"] as U_Member).ID;
            question.Phone = (Session["CurrentUser"] as U_Member).Mobilenumber;

            int? pq = _pro.GetQIdByMemberId(question.MemberId.ToString(), null);

            question.ReplyId = pq > 0 ? pq : null;

            if (question.RMemberId != null)
            {
                question.ReplyTime = DateTime.Now;
            }

            int result = _pro.SubmitQuestion(question);

            if (result > 0)
            {
                msg.Status = 1;
                msg.Message = "问题提交成功，请耐心等待回复...";
                msg.Data = "/Default/Detail/" + question.ProjectId;
            }
            else
            {
                msg.Status = -1;
                msg.Message = "提交失败！";
            }

            return Json(msg);
        }

        #endregion


        public ActionResult test()
        {
            string hehe = "quanjuzc_" + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(0, 9999);
            return View();
        }


    }
}
